<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>考试管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 顶部搜索框区域 -->
      <div class="area">
        <div class="input-area">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getTestsList"
          >
            <el-button
              type="primary"
              slot="append"
              icon="el-icon-search"
              @click="getTestsList"
            ></el-button>
          </el-input>
          <el-button type="primary" @click="gotoAddTests"
            >添加考试/小测</el-button
          >
        </div>

        <!-- <el-col :span="3">
          <el-button type="primary" @click="deleteTests"
            >删除考试/小测</el-button
          >
        </el-col> -->
        <!-- 考试小测选择器 -->
        <div class="select-area">
          <el-select v-model="value" placeholder="选择考试/小测">
            <el-option
              popper-append-to-body="false"
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <!-- 考试表格区域 -->
      <el-table
        :data="testsList"
        height="450"
        stripe
        border
        @selection-change="handleSelectionChange1"
        v-if="value == 1"
      >
        <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="description" label="考试/小测">
        </el-table-column>
        <el-table-column prop="testId" label="类型" width="150px">
          <template slot-scope="scope">
            <el-tag type="danger">
              考试
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-s-grid"
              size="mini"
              @click="creatQrCode(scope.row)"
              >二维码</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="gotoEditTests(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-delete"
              size="mini"
              @click="deleteTest(scope.row.testId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 小测列表表格 -->
      <el-table
        :data="quizsList"
        height="450"
        stripe
        border
        @selection-change="handleSelectionChange2"
        v-else
      >
        <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="description" label="考试/小测">
        </el-table-column>
        <el-table-column prop="testId" label="类型" width="150px">
          <template slot-scope="scope">
            <el-tag type="danger">
              小测
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="gotoEditTests(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-delete"
              size="mini"
              @click="deleteQuiz(scope.row.quizId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, prev, pager, next, jumper"
        :total="value == '1' ? total1 : total2"
      >
      </el-pagination>
    </el-card>
    <!-- 展示签到二维码对话框 -->
    <el-dialog
      title="考试二维码"
      :visible.sync="qiandaoVisible"
      @close="closeQiandaoVisible"
    >
      <div class="qrcodeArea">
        <div class="qrcode" id="qrcode" ref="qrCodeUrl"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";
export default {
  data() {
    return {
      // 打开签到二维码对话框
      qiandaoVisible: false,
      // 二维码url
      textUrl: "",
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 15
      },
      total1: 0,
      total2: 0,
      //   考试列表
      testsList: [],
      //小测列表
      quizsList: [],
      //   选择考试还是小测
      options: [
        {
          value: "1",
          label: "考试"
        },
        {
          value: "2",
          label: "小测"
        }
      ],
      value: "1",
      // 删除考试/小测
      testDeleteIdList: []
    };
  },
  methods: {
    // 生成考试二维码
    async creatQrCode(row) {
      this.qiandaoVisible = true;
      let that = this;
      let res = "";
      // 获取考试url
      if (row.testId) {
        const { data: res1 } = await this.$http.get(
          "test/getTestQuestionCode/" + row.testId
        );
        res = res1;
      }
      console.log(res);
      if (res.code !== 200) {
        this.qiandaoVisible = false;
        return this.$message.error("获取二维码失败！");
      }
      this.textUrl = res.data;
      setTimeout(() => {
        let qrcode = new QRCode(that.$refs.qrCodeUrl, {
          text: this.textUrl, // 需要转换为二维码的内容
          width: 500,
          height: 500,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.H
        });
      }, 0);
    },
    // 关闭签到二维码对话框时将上次生成的二维码清空
    closeQiandaoVisible() {
      document.getElementById("qrcode").innerHTML = "";
    },
    // 获取考试列表
    async getTestsList() {
      if (this.queryInfo.query && this.value == 1) {
        const { data: res1 } = await this.$http.get(
          `test/fuzzyQueryTest/${this.queryInfo.query}/${this.queryInfo.pagenum}`
        );
        if (res1.code !== 200) return this.$message.error("查找失败！");
        this.testsList = res1.data.testVoList;
        this.total1 = res1.data.total;
        return this.$message.success("查找成功！");
      }
      if (this.queryInfo.query && this.value == 2) {
        const { data: res2 } = await this.$http.get(
          `quiz/fuzzyQueryQuiz/${this.queryInfo.query}/${this.queryInfo.pagenum}`
        );
        if (res2.code !== 200) return this.$message.error("查找失败！");
        this.quizsList = res2.data.quizVoList;
        this.total2 = res2.data.total;
        return this.$message.success("查找成功！");
      }
      // 获取考试列表
      const { data: res1 } = await this.$http.get(
        "test/getTestVo/" + this.queryInfo.pagenum
      );
      if (res1.code !== 200) return this.$message.error("获取考试列表失败！");
      this.testsList = res1.data.testVoList;
      // 获取小测列表
      const { data: res2 } = await this.$http.get(
        "quiz/getQuizVo/" + this.queryInfo.pagenum
      );
      if (res2.code !== 200) return this.$message.error("获取小测列表失败！");
      this.quizsList = res2.data.quizVoList;
      this.total1 = res1.data.total;
      this.total2 = res2.data.total;
    },
    // 多选勾选时将对应testId添加到删除序列
    handleSelectionChange1(rows) {
      this.testDeleteIdList = [];
      rows.forEach(item => {
        this.testDeleteIdList.push(item.testId);
      });
      console.log(this.testDeleteIdList);
    },
    // 多选勾选时将对应quizId添加到删除序列
    handleSelectionChange2(rows) {
      this.testDeleteIdList = [];
      rows.forEach(item => {
        this.testDeleteIdList.push(item.quizId);
      });
      console.log(this.testDeleteIdList);
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getTestsList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getTestsList();
    },
    // 删除单个考试
    async deleteTest(id) {
      const deleteResult = await this.$confirm("是否删除该考试?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err);
      if (deleteResult === "cancel") return this.$message.info("取消删除！");
      const { data: res } = await this.$http.get("test/deleteTest/" + id);
      console.log(res);
      if (res.code !== 200) return this.$message.error("删除考试失败！");
      this.$message.success("删除成功！");
      this.getTestsList();
    },
    // 删除单个小测
    async deleteQuiz(id) {
      const deleteResult = await this.$confirm("是否删除该小测?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err);
      if (deleteResult === "cancel") return this.$message.info("取消删除！");
      const { data: res } = await this.$http.get("quiz/deleteQuiz/" + id);
      console.log(res);
      if (res.code !== 200) return this.$message.error("删除小测失败！");
      this.$message.success("删除成功！");
      this.getTestsList();
    },
    //   删除多个考试/小测
    async deleteTests() {
      const deleteResult = await this.$confirm("是否删除该考试/小测?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err);
      if (deleteResult === "cancel") return this.$message.info("取消删除！");
      if (this.value == "1") {
      } else {
      }
      //   const { data: res } = await this.$http.delete("goods/" + id);
      //   if (res.meta.status !== 200) return this.$message.error("删除商品失败！");
      this.$message.success("删除成功！");
      this.getTestsList();
    },
    // 跳转到添加考试组件
    gotoAddTests() {
      this.$router.push("/test/addtest");
    },
    // 跳转到编辑考试组件
    gotoEditTests(row) {
      console.log(row);
      //   将testId保存到本地
      if (this.value == 1) {
        window.sessionStorage.setItem("testToken", row.token);
        window.sessionStorage.setItem("testId", row.testId);
      } else window.sessionStorage.setItem("quizId", row.quizId);
      window.sessionStorage.setItem("value", this.value);
      window.sessionStorage.setItem("description", row.description);
      this.$router.push("/test/edittest");
    }
  },
  created() {
    this.getTestsList();
  }
};
</script>

<style lang="less" scoped>
.el-table {
  margin: 20px 0;
}
// 二维码区域
.qrcodeArea {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .qrcode {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
    width: 500px;
    height: 500px;
    padding: 6px;
    box-sizing: border-box;
  }
}

.input-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 46%;
  .el-input {
    margin-right: 10px;
  }
}
.select-area {
  width: 10%;
}
.area {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>